/* Copyright (C) 2009 Christofer Jonsson
 *
 * This file is part of FNM.
 *
 * FNM is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FNM is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FNM.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "fnm_error.h"
#include "fnm_cmd.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FLAG_LOWER_CASE 'l'
#define FLAG_UPPER_CASE 'u'
#define FLAG_REPLACE    'r'
#define FLAG_VERSION    'v'

static void cmd_caller(int nargs, const char **args, fnm_cmd_func_t cmd);
static void check_arg_count(int argc);
static void check_flag(const char *flag);

int main(int argc, const char **argv)
{
   const char *flag = NULL;
   const char **args;
   int nargs = 0;

   check_arg_count(argc);
   check_flag(argv[1]);

   flag = argv[1];
   nargs = argc - 2;
   args = argv + 2;

   switch (flag[1])
   {
      case FLAG_LOWER_CASE:
      {
	 cmd_caller(nargs, args, fnm_cmd_lower_case);
	 break;
      }
      case FLAG_UPPER_CASE:
      {
	 cmd_caller(nargs, args, fnm_cmd_upper_case);
	 break;
      }
      case FLAG_REPLACE:
      {
	 cmd_caller(nargs, args, fnm_cmd_replace);
	 break;
      }
      case FLAG_VERSION:
      {
	 fnm_cmd_version();
	 break;
      }
      default:
      {
	 FNM_ERROR("Unknown input flag: %s", flag);
	 exit(EXIT_FAILURE);
      }
   }
   
   return 0;
}

static void cmd_caller(int nargs, const char **args, fnm_cmd_func_t cmd)
{
   if (cmd(nargs, args, rename) == FNM_FAILURE)
   {      
      exit(EXIT_FAILURE);
   }
}

static void check_arg_count(int argc)
{
   const int min_args = 2;

   if (argc < min_args)
   {
      FNM_ERROR("Too few input arguments");
      exit(EXIT_FAILURE);
   }
}

static void check_flag(const char *flag)
{
   const size_t flag_length = 2;

   if (strlen(flag) != flag_length)
   {
      FNM_ERROR("Illegal input flag: %s", flag);
      exit(EXIT_FAILURE);
   }
}
